package com.ultrawise.survey.common.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;

import com.ultrawise.survey.common.utils.StringUtils;
import com.ultrawise.survey.contants.SurveyConstants;
import com.ultrawise.survey.module.user.vo.TSurveyInfoUsers;

public class UserLoginFilter implements Filter {

	private static Map noFilterUrlMap = null;

	public void destroy() {
		//System.out.println(":::debug:::userlogin:::filter is destroy.");
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		HttpSession session = request.getSession();
		//测试过程，过滤器自己增加登录用户信息
//		TSurveyInfoUsers us = new TSurveyInfoUsers(1);
//		us.setUs_login("admin");
//		session.setAttribute(SurveyConstants.LOGINED_USER, us);
//		session.setAttribute(SurveyConstants.LOGIN_SESSION_LOGINNAME, "admin");
		
		TSurveyInfoUsers user = (TSurveyInfoUsers) session
				.getAttribute(SurveyConstants.LOGINED_USER);

		String uri = StringUtils.getURI(request.getRequestURI(),
				request.getContextPath());

		if (uri == null || uri.trim().length() <= 0 || isIncludeMapURI(uri)) {
			//System.out.println("nofilter--uri::"+uri);
		} else {
			//System.out.println("yesfilter--uri::"+uri);
			if (user == null || user.getId() == null) {
				// 提示不能访问
				// HttpServiceUtil.showMessage(response,
				// "错误信息:[您无权访问,请与管理员联系.]；页面将3秒自动返回登录页面。" +
				// "<meta http-equiv=refresh content=\"3;url="+request.getContextPath()+"/login.htm\">");
				
				RequestDispatcher dispatcher = request.getRequestDispatcher("/symanage/msg.jsp");
				request.setAttribute("message", "错误信息:[您无权访问或者登陆已超时，请重新登陆.]。");
				request.setAttribute("url", request.getContextPath()+"/login.htm");
				dispatcher.forward(request, response);
				return;
			}
		}
		chain.doFilter(request, response);
		return;

	}

	public void init(FilterConfig filterConfig) throws ServletException {
		noFilterUrlMap = new HashMap();
		if (filterConfig.getInitParameter("noFilterUrl") != null
				&& !filterConfig.getInitParameter("noFilterUrl").trim()
						.equalsIgnoreCase("")) {
			String[] authURL = filterConfig.getInitParameter("noFilterUrl")
					.split(",");
			for (int i = 0; i < authURL.length; i++)
				noFilterUrlMap.put(authURL[i], authURL[i]);
		}

	}

	private boolean isIncludeMapURI(String uri) {
		// System.out.println("notAuthUrlMap:"
		// + ((notAuthUrlMap != null) ? notAuthUrlMap.size() + "::" +
		// notAuthUrlMap : null));
		// WTX--System.out.println("access uri:" + uri);
		if (noFilterUrlMap != null && noFilterUrlMap.size() > 0) {
			for (Iterator i = noFilterUrlMap.entrySet().iterator(); i.hasNext();) {
				Map.Entry entry = (Map.Entry) i.next();
				if (uri.startsWith((String) entry.getKey())) {
					return true;
				}
			}
		}
		return false;
	}

}
